# adoption from chapter 05 generate data.r
path_data=normalizePath('../../2021-2022(2)')
class_data_files = list.files(path_data)

library(readxl)
library(haven)
library(expss)
class_id = 2
xls_file = normalizePath(file.path(path_data,class_data_files[class_id]))
df_class_data = read_excel(xls_file,col_names = c('id','student_id','name'))

generate_data = function(seed_num,student_name){
  set.seed(seed_num)
  output_folder = file.path(getwd(),'data','chapter06',paste(seed_num,student_name,sep="_"))
  dir.create(file.path(getwd(),'data','chapter06'))
  dir.create(output_folder)
  
  complications1 = c(
    rep(1,3),
    rep(2,5),
    rep(3,6),
    rep(4,7),
    rep(5,18)
  )
  complications2 = c(
    rep(1,5),
    rep(2,3),
    rep(3,4),
    rep(4,3),
    rep(5,25)
  )
  group = c(rep(1,length(complications1)),rep(2,length(complications2)))
  group_labels = c('观察组','对照组')
  
  complications_labels = c('Frey综合征','暂时性面瘫','涎瘘','耳垂区麻木','无并发症')
  
  complications = c(complications1,complications2)
  
  library(expss)
  library(haven)
  library(dplyr)
  
  df = data.frame(
    group=factor(group,labels = group_labels),
    complications=factor(complications,labels=complications_labels)
  )
  
  df = apply_labels(df,group='分组',complications='并发症')
  write_sav(df,file.path(output_folder,'ch6_exe1.sav'))
  return(df)
}

for (row in 1:nrow(df_class_data)){
  student_id =as.numeric(df_class_data[row,'student_id']) %% 1000000
  name=df_class_data[row,'name']
  generate_data(student_id,name)
}
